package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.util.QueryObject;
import cn.wolfcode.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        //保存时设置
        //设置操作人
        notice.setIssuer((Employee) SecurityUtils.getSubject().getPrincipal());
        //设置操作时间
        notice.setPubdate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        //删除公告被员工阅读的中间表信息
        noticeMapper.deleteEmployeeReadNotice(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit

        //获取当前登陆对象
        Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
        //查询当前登陆对象的公告查看情况
        List<Long> readList = noticeMapper.selectForReadList(currentUser.getId());

        for (Notice notice : notices) {
            //根据公告id是否存在公告查看情况集合中判断当前用户是否阅读过当前公告
            //存在说明看过则设置查看情况为true,否则反之
            notice.setRead(readList.contains(notice.getId()));
        }
        return new PageInfo<Notice>(notices);
    }



    @Override
    public void saveRead(Long noticeId) {
        //获取当前登陆对象
        Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
        //查询当前登陆对象的公告查看情况
        List<Long> readList = noticeMapper.selectForReadList(currentUser.getId());
        //判断是否读过
        if (!readList.contains(noticeId)){
            //没读过就保存当前登陆用户阅读过公告情况
            noticeMapper.saveRead(noticeId,currentUser.getId());
        }
    }
}
